package com.haois.ws.common.exception;


import com.haois.ws.common.constant.Reply;
import com.haois.ws.common.enums.ApiResultEnum;
import com.haois.ws.common.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理controller异常
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger logger = LoggerFactory
            .getLogger(ControllerExceptionHandler.class);

    /**
     * 处理refresh_token异常，重新登录
     */
    @ExceptionHandler(InvalidRefreshTokenException.class)
    public ModelAndView invalidRefreshToken(InvalidRefreshTokenException exception) {
        logger.debug("refreshToken过期，重新登录,error:{}", exception);
        return new ModelAndView("/user/login");
    }

    /**
     * 处理SessionOutException异常
     */
    @ExceptionHandler(OutException.class)
    public ModelAndView errorPage(OutException exception) {
        logger.debug("ErrCode:{},ErrMsg:{}", exception.getCode(), exception.getMsg());
        if (ApiResultEnum.API_16.getCode().equals(exception.getCode())) {
            return GetModelAndView.getDataErrorPage();
        } else {
            return GetModelAndView.getSessionOutPage();
        }
    }

    @ResponseBody
    @ExceptionHandler(ErrorException.class)
    public String errorException(ErrorException e) {
        logger.debug("ErrorException:{}:{}", e.getErrorCode(), e.getMessage());
        return new Reply(ApiResultEnum.API_10, e.getMessage()).toJson();
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionMv(Exception e, HttpServletRequest request, HttpServletResponse response) {
        e.printStackTrace();
        if (HttpUtil.isAjax(request)) {
            logger.info("Ajax请求出现异常:{}", e.getMessage());
            HttpUtil.renderJson(response, new Reply(ApiResultEnum.API_10));
            GetModelAndView.getErrorPage().addObject("tips", e.getMessage());
            return null;
        } else {
            logger.info("页面请求出现异常:{}", e.getMessage());
            return GetModelAndView.getErrorPage();
        }
    }
}
